import { defineStore } from 'pinia'
import { ref } from 'vue'
import * as mars3d from 'mars3d'

export const useLayerStore = defineStore('layer', () => {
  const layers = ref([])
  const nextLayerId = ref(1)
  const map = ref(null)

  // 设置地图实例
  const setMap = (mapInstance) => {
    map.value = mapInstance
    console.log('地图实例已设置:', mapInstance)
    
    // 为已存在的图层创建实例
    layers.value.forEach(layer => {
      if (!layer.layerInstance) {
        createLayerInstance(layer)
      }
    })
  }

  // 获取 Mars3D 引用的辅助函数
  const getMars3D = () => {
    // 尝试多种方式获取 Mars3D
    if (window.mars3d) {
      return window.mars3d
    }
    
    // 如果通过 import 导入了 mars3d
    if (typeof mars3d !== 'undefined') {
      return mars3d
    }
    
    // 尝试从全局获取
    if (typeof window !== 'undefined' && window.Mars3D) {
      return window.Mars3D
    }
    
    // 最后尝试从地图实例获取
    if (map.value && map.value.mars3d) {
      return map.value.mars3d
    }
    
    throw new Error('无法获取 Mars3D 引用')
  }

  // 添加图层
  const addLayer = async (layerConfig) => {
    try {
      console.log('添加图层配置:', layerConfig)
      
      const layer = {
        id: nextLayerId.value++,
        name: layerConfig.name || `图层${nextLayerId.value - 1}`,
        type: layerConfig.type,
        visible: layerConfig.visible !== false,
        zIndex: layerConfig.zIndex || layers.value.length,
        layerInstance: null,
        ...layerConfig
      }
      
      layers.value.push(layer)
      
      // 创建Mars3D图层实例
      if (map.value) {
        await createLayerInstance(layer)
      } else {
        console.warn('地图实例未设置，图层将在地图加载后创建')
      }
      
      return layer
    } catch (error) {
      console.error('添加图层失败:', error)
      throw error
    }
  }

  // 创建图层实例
  const createLayerInstance = async (layer) => {
    if (!map.value) {
      console.warn('地图实例未设置')
      return
    }

    try {
      const Mars3D = getMars3D()
      console.log('获取到 Mars3D:', Mars3D)
      
      let layerInstance = null
      
      console.log(`创建${layer.type}类型图层:`, layer.name)
      
      switch (layer.type) {
        case '3dtiles':
          layerInstance = new Mars3D.layer.TilesetLayer({
            name: layer.name,
            url: layer.url,
            show: layer.visible,
            maximumScreenSpaceError: layer.maximumScreenSpaceError || 16,
            maximumMemoryUsage: layer.maximumMemoryUsage || 512,
            flyTo: true
          })
          break
          
        case 'tms':
          // 使用 XyzLayer 替代 TmsLayer
          layerInstance = new Mars3D.layer.XyzLayer({
            name: layer.name,
            url: layer.url,
            show: layer.visible,
            minimumLevel: layer.minimumLevel || 0,
            maximumLevel: layer.maximumLevel || 18
          })
          break
          
        case 'wms':
          layerInstance = new Mars3D.layer.WmsLayer({
            name: layer.name,
            url: layer.url,
            layers: layer.layers,
            show: layer.visible,
            parameters: {
              service: 'WMS',
              version: '1.1.1',
              request: 'GetMap',
              format: layer.format || 'image/png',
              transparent: layer.transparent !== false,
              ...layer.parameters
            }
          })
          break
          
        case 'geojson':
          console.log('创建GeoJSON图层，数据源:', layer.dataSource)
          
          const geoJsonOptions = {
            name: layer.name,
            show: layer.visible,
            flyTo: true,
            symbol: {
              type: 'polygon',
              styleOptions: {
                fill: true,
                fillColor: layer.fillColor || '#ffff00',
                fillOpacity: layer.fillOpacity || 0.6,
                outline: true,
                outlineColor: layer.outlineColor || '#ffffff',
                outlineWidth: layer.outlineWidth || 2
              }
            }
          }

          // 根据数据源类型设置数据
          if (layer.url) {
            geoJsonOptions.url = layer.url
          } else if (layer.data) {
            geoJsonOptions.data = layer.data
          } else if (layer.geoJsonData) {
            geoJsonOptions.data = layer.geoJsonData
          } else {
            throw new Error('GeoJSON图层缺少数据源')
          }

          layerInstance = new Mars3D.layer.GeoJsonLayer(geoJsonOptions)
          
          // 为GeoJSON图层添加加载完成事件监听
          layerInstance.on(Mars3D.EventType.load, () => {
            console.log(`GeoJSON图层 "${layer.name}" 加载完成`)
          })
          
          layerInstance.on(Mars3D.EventType.loadError, (error) => {
            console.error(`GeoJSON图层 "${layer.name}" 加载失败:`, error)
          })
          break
          
        default:
          throw new Error(`不支持的图层类型: ${layer.type}`)
      }
      
      if (layerInstance) {
        console.log('图层实例创建成功，准备添加到地图')
        
        // 保存图层实例引用
        layer.layerInstance = layerInstance
        
        // 添加到地图
        map.value.addLayer(layerInstance)
        console.log(`图层 "${layer.name}" 已添加到地图`)
        
        // 对于3DTiles和GeoJSON，尝试飞到图层位置
        if (layer.type === '3dtiles' || layer.type === 'geojson') {
          setTimeout(() => {
            try {
              if (layerInstance.flyTo) {
                layerInstance.flyTo()
              }
            } catch (e) {
              console.warn('无法飞到图层:', e)
            }
          }, 1000)
        }
        
      } else {
        throw new Error('图层实例创建失败')
      }
      
    } catch (error) {
      console.error(`创建图层 "${layer.name}" 失败:`, error)
      throw error
    }
  }

  // 删除图层
  const removeLayer = (layerId) => {
    const index = layers.value.findIndex(l => l.id === layerId)
    if (index > -1) {
      const layer = layers.value[index]
      console.log(`删除图层: ${layer.name}`)
      
      if (layer.layerInstance && map.value) {
        try {
          map.value.removeLayer(layer.layerInstance)
          console.log(`图层 "${layer.name}" 已从地图移除`)
        } catch (error) {
          console.error('从地图移除图层失败:', error)
        }
      }
      layers.value.splice(index, 1)
    }
  }

  // 切换图层可见性
  const toggleLayerVisible = (layerId) => {
    const layer = layers.value.find(l => l.id === layerId)
    if (layer) {
      layer.visible = !layer.visible
      console.log(`切换图层 "${layer.name}" 可见性:`, layer.visible)
      
      if (layer.layerInstance) {
        layer.layerInstance.show = layer.visible
      }
    }
  }

  // 设置图层顺序
  const setLayerOrder = (layerId, newIndex) => {
    const layerIndex = layers.value.findIndex(l => l.id === layerId)
    if (layerIndex > -1) {
      const layer = layers.value.splice(layerIndex, 1)[0]
      layers.value.splice(newIndex, 0, layer)
      
      // 更新Mars3D中的图层顺序
      if (map.value && layer.layerInstance) {
        try {
          map.value.removeLayer(layer.layerInstance)
          map.value.addLayer(layer.layerInstance)
        } catch (error) {
          console.error('更新图层顺序失败:', error)
        }
      }
    }
  }

  // 清空所有图层
  const clearLayers = () => {
    console.log('清空所有图层')
    layers.value.forEach(layer => {
      if (layer.layerInstance && map.value) {
        try {
          map.value.removeLayer(layer.layerInstance)
        } catch (error) {
          console.error('移除图层失败:', error)
        }
      }
    })
    layers.value.splice(0)
    console.log('所有图层已清空')
  }

  // 获取图层
  const getLayer = (layerId) => {
    return layers.value.find(l => l.id === layerId)
  }

  return {
    layers,
    addLayer,
    removeLayer,
    toggleLayerVisible,
    setLayerOrder,
    setMap,
    clearLayers,
    getLayer
  }
})